#!/usr/bin/env python

from __future__ import print_function
import sys
import os
import re
import time
import logging
import platform
import argparse


def _get_module_list_from_pythonpath():
    res = []
    re_exp = re.compile(r"^plugin.*\.py$")

    for folder in os.environ.get("PYTHONPATH", "").split(":"):
        if not os.path.isdir(folder):
            continue
        for name in os.listdir(folder):
            if not re_exp.match(name):
                continue
            name = os.path.splitext(name)[0]
            if name not in res:
                res.append( name )

    return res


def _load_script_from_repo(subparsers):
    '''load plugins'''
    import importlib
    re_exp = re.compile(r"^plugin.*\.py$")
    names = _get_module_list_from_pythonpath()

    for name in names:
        try:
            module = importlib.import_module(name)
            add_parser = getattr(module, "add_parser")
            add_parser(subparsers)

        except(ImportError, AttributeError) as exp:
            print("ERROR:", exp)
            pass


def main():

    logging.basicConfig(stream=sys.stdout, format='%(asctime)s - %(message)s', level=logging.INFO)

    parser = argparse.ArgumentParser(
        description="A GIT helper script.")
    subparsers = parser.add_subparsers(help='sub-commands help')

    # local plugins from git template folder and current project folder.
    _load_script_from_repo(subparsers)

    args = parser.parse_args()
    try:
        func = args.func
    except AttributeError:
        print("ERROR: too few arguments")
        exit(100)

    logging.debug("Command line: {}".format(args))
    func(args)
    logging.debug("Done.\n")


if __name__ == '__main__':
    main()
